import { compose, isEmpty } from "@/utils";
import { getFullImgPath } from "@/utils/constants";
import { dateFormat } from "@/utils/date";
import { NImage, NSpace, NTag } from "naive-ui";

const defaultEmptyValue = "--";
const catchEmpty = (val: any) => {
  if (val == null || isEmpty(val)) return defaultEmptyValue;
  return val;
};

const text = (str: string) => {
  return <span>{str}</span>;
};
const tag = (str: string) => {
  return <NTag>{str}</NTag>;
};

export const composeRender = ({
  isCatchEmpty = true,
  valFunc = (v: any) => v,
  isDateFormat = false,
  isTag = false,
}) => {
  const funcs: ((v: any) => any)[] = [];
  if (isCatchEmpty) funcs.push(catchEmpty);
  if (valFunc) funcs.push(valFunc);
  if (isDateFormat) funcs.push(dateFormat);
  funcs.push(isTag ? tag : text);

  return compose(...funcs);
};

export const defaultRender = ({ rowData, key }: any) => {
  return composeRender({})(rowData[key]);
};

export const boolRender = ({ rowData, key }: any) => {
  return composeRender({ valFunc: (v) => (v ? "是" : "否") })(rowData[key]);
};

export const secondsTimestampRender = ({ rowData, key }: any) => {
  return composeRender({ valFunc: (v) => v * 1000, isDateFormat: true })(
    rowData[key]
  );
};

export const dateRender = ({ rowData, key }: any) => {
  return composeRender({ isDateFormat: true })(rowData[key]);
};

export const enumRender =
  (dict: any) =>
  ({ rowData, key }: any) => {
    return composeRender({ valFunc: (v) => dict[v], isTag: true })(
      rowData[key]
    );
  };

export const listRender = ({ rowData, key }: any) => {
  if (rowData[key] == null || isEmpty(rowData[key])) return defaultEmptyValue;
  return (
    <NSpace>
      {rowData[key].map((v: any) => composeRender({ isTag: true })(v))}
    </NSpace>
  );
};

export const commaSeparateStringListRender = ({ rowData, key }: any) => {
  if (rowData[key] == null || isEmpty(rowData[key])) return defaultEmptyValue;
  return (
    <NSpace>
      {rowData[key]
        .split(",")
        .map((v: any) => composeRender({ isTag: true })(v))}
    </NSpace>
  );
};

export const imageRender = (imgPath: string | undefined) => {
  if (imgPath) {
    const src = getFullImgPath(imgPath);
    return <NImage src={src} width={32} height={32}></NImage>;
  }
  return defaultEmptyValue;
};
